package com.irdstudio.efp.limit.service.common;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.irdstudio.efp.cus.service.vo.CusPrelistRiskInfoVO;
import com.irdstudio.efp.cus.service.vo.CusRptCdtCardInfoVO;
import com.irdstudio.efp.cus.service.vo.CusRptLoanInfoVO;
import com.irdstudio.efp.cus.service.vo.CusRptOverdueDetailVO;
import com.irdstudio.efp.cus.service.vo.CusRptPromptInfoVO;
import com.irdstudio.efp.cus.service.vo.CusRptQueryDetailVO;
import com.irdstudio.efp.cus.service.vo.CusRptResultVO;
import com.irdstudio.basic.framework.core.constant.BaseConstant;
import com.irdstudio.basic.framework.core.util.DateTool;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.efp.limit.service.domain.LmtPrelist;
import com.irdstudio.efp.rule.common.enumeration.CardStatus;
import com.irdstudio.efp.rule.common.enumeration.CreditCardType;
import com.irdstudio.efp.rule.common.enumeration.CreditQueryType;
import com.irdstudio.efp.rule.common.enumeration.GuaranteeType;
import com.irdstudio.efp.rule.common.enumeration.LoanStatus;
import com.irdstudio.efp.rule.common.enumeration.LoanType;
import com.irdstudio.efp.rule.common.enumeration.RiskClassfyType;
import com.irdstudio.efp.rule.service.vo.BankInnerLoanEntity;
import com.irdstudio.efp.rule.service.vo.CreditCardEntity;
import com.irdstudio.efp.rule.service.vo.CreditCardOverdueEntity;
import com.irdstudio.efp.rule.service.vo.CreditQueryEntity;
import com.irdstudio.efp.rule.service.vo.PersonalCreditEntity;
import com.irdstudio.efp.rule.service.vo.RuleArgsEntity;

public class RptRecod2RuleArgsEntityUtil {

	private static Logger logger = LoggerFactory.getLogger(RptRecod2RuleArgsEntityUtil.class);

	/**
	 * 通过征信信息与贷款信息获取规则参数类
	 * 
	 * @param cusRptResultVO
	 * @param cusPrelistRiskInfoVo
	 * @return
	 * @throws Exception 
	 */
	public static RuleArgsEntity getRuleArgsByRptRecod(CusRptResultVO cusRptResultVO,
			CusPrelistRiskInfoVO cusPrelistRiskInfoVo ,String firstDisbDate) throws Exception {

		String preSerno = "";
		LmtPrelist lmtPrelist = null;
		BigDecimal creditCardTotalAmt = new BigDecimal("0");// 信用卡授信总额度
		BigDecimal sixAvgUsedAmt = new BigDecimal("0");// 所有的信用卡最近6个月平均使用额度

		CusRptPromptInfoVO cusRptPromptInfoVO = cusRptResultVO.getCusRptPromptInfoVo();// 汇总信息
		List<CusRptCdtCardInfoVO> cardInfos = cusRptResultVO.getCusRptCdtCardInfoVo();// 征信信用卡信息
		List<CusRptLoanInfoVO> loanInfos = cusRptResultVO.getCusRptLoanInfoVo();// 征信贷款信息
		List<CusRptOverdueDetailVO> cusRptOverdueDetailVos = cusRptResultVO.getCusRptOverdueDetailVo();// 逾期记录，多条记录
		List<CusRptQueryDetailVO> cusRptQueryDetailVo = cusRptResultVO.getCusRptQueryDetailVo();// 历史查询记录，多条记录
		int cardOverDueLJ = 0; // 24个月内信用卡逾期累计
		int cardOverDueMaxLX = 0;// 24个月内信用卡最大连续逾期

		// 准备数据
		RuleArgsEntity ruleArgsEntity = new RuleArgsEntity();
		PersonalCreditEntity personalCreditEntity = new PersonalCreditEntity();// 征信信息

		/*************** 查询征信报告次数 start ***************/
		List<CreditQueryEntity> querys = new ArrayList<>();// 征信报告查询信息列表
		if (Objects.nonNull(cusRptQueryDetailVo)) {
			for (CusRptQueryDetailVO vo : cusRptQueryDetailVo) {
				CreditQueryEntity creditQueryEntity = new CreditQueryEntity();
				creditQueryEntity.setQueryReason(judgeQueryReason(vo.getQueryCase()));// 贷款查询原因
				creditQueryEntity.setQueryDate(getQueryDate(vo.getQueryTime()));// 查询日期 yyyy-MM-dd
				creditQueryEntity.setBankNo(getBankNo(vo.getQueryUser()));// 卡归属银行代码/或者中文描述
				creditQueryEntity.setOperator(getQueryUser(vo.getQueryUser()));// 操作员
				querys.add(creditQueryEntity);
			}
		}
		personalCreditEntity.setQuerys(querys);// 征信报告查询信息列表
		/*************** 查询征信报告次数 end ***************/

		/*************** 个人征信卡信息对象，含贷款/贷记卡/准贷记卡 start ***************/
		List<CreditCardEntity> cards = new ArrayList<>();
		String regex = "\\d";// 匹配数字
		// String baseDate =
		// TimeUtil.getTimeStampByPattern(DateFormatConstant.YEAR_MONTH);//当月 yyyy-MM
		// baseDate = baseDate + "-01";//转成当月1号
		// 贷款
		if (Objects.nonNull(loanInfos)) {
			for (CusRptLoanInfoVO infoVO : loanInfos) {
				String endDate = infoVO.getRepay24stateEnd();
				endDate = endDate.replaceAll("\\D", "") + "01";
				endDate = DateTool.formatDate(endDate, DateTool.PATTERN_DEFAULT);
				CreditCardEntity creditCardEntity = new CreditCardEntity();
				creditCardEntity.setStartYearMonth(infoVO.getRepay24stateStart());// 还款的开始日期
				creditCardEntity.setEndYearMonth(infoVO.getRepay24stateEnd());// 还款的结束日期
				creditCardEntity.setLoanStatus(getLoanStatus(infoVO.getLoanState()));// 贷款状态
				creditCardEntity.setLoanBalAmt(infoVO.getLoanBalance());// 贷款余额
				creditCardEntity.setCardType(CreditCardType.LOAN_CARD);
				creditCardEntity.setLoanType(getLoanType(infoVO.getLoanPrd()));// 贷款类型
				creditCardEntity.setTotalAmt(infoVO.getLoanAmount());// 总额
				creditCardEntity.setBankNo(infoVO.getLoanOrg());// 行号
				creditCardEntity.setRiskClassfy(getRiskClassfyType(infoVO.getFiveLevel()));// 风险分类
				creditCardEntity.setGuarType(getGuaranteeType(infoVO.getGuarType()));// 担保方式
				creditCardEntity.setCurrMonthUsedAmt((infoVO.getsPaymentAmt()));// 当前月应还金额
				creditCardEntity.setLastRepayNum(infoVO.getRepaymentCyc());// 剩余还款期数
				List<CreditCardOverdueEntity> overdueInfos = new ArrayList<>();
				String repay_24state = infoVO.getRepay24state();// 近24个月还款情况
				if (StringUtil.isNotEmpty(repay_24state)) {
					int len = repay_24state.length();
					for (int i = 0; i < len; i++) {
						CreditCardOverdueEntity overdueEntity = new CreditCardOverdueEntity();
						char c = repay_24state.charAt(len - 1 - i);
						String yearMonth = TimeUtil.addMonth(endDate, 0 - i).replaceAll("-", "").substring(0, 6);// yyyyMM
						overdueEntity.setOverDueDate(yearMonth);// 逾期月份
						// 如果是数字
						if (String.valueOf(c).matches(regex)) {
							overdueEntity.setLastOverdueMonth(Integer.parseInt(String.valueOf(c)));// 逾期持续月份
						} else {
							overdueEntity.setLastOverdueMonth(0);// 逾期持续月份
						}
						overdueInfos.add(overdueEntity);
					}
				}
				// 封装3-5年对应贷款的逾期信息
				if (Objects.nonNull(cusRptOverdueDetailVos)) {
					for (CusRptOverdueDetailVO cusRptOverdueDetailVO : cusRptOverdueDetailVos) {
						if (infoVO.getLoanId().equals(cusRptOverdueDetailVO.getLoanId())) {
							CreditCardOverdueEntity overdueEntity = new CreditCardOverdueEntity();
							overdueEntity.setLastOverdueMonth(cusRptOverdueDetailVO.getLastOverdueMonth());
							overdueEntity.setOverDueAmt(cusRptOverdueDetailVO.getOverdueAmt());
							overdueEntity.setOverDueDate(cusRptOverdueDetailVO.getOverdueMonth());
							overdueInfos.add(overdueEntity);
						}
					}
				}
				creditCardEntity.setOverdueInfos(overdueInfos);
				// 设置当前逾期情况
				CreditCardOverdueEntity creditCardOverdueEntity = new CreditCardOverdueEntity();
				creditCardOverdueEntity.setOverDueAmt(infoVO.getCurrOverdueAmt());// 当前逾期金额
				creditCardOverdueEntity.setLastOverdueMonth(infoVO.getCurrOverdueNum());// 当前逾期期数
				creditCardEntity.setCurrentOver(creditCardOverdueEntity);
				cards.add(creditCardEntity);
			}
		}

		// 信用卡
		if (Objects.nonNull(cardInfos)) {
			for (CusRptCdtCardInfoVO cardInfoVO : cardInfos) {
				String endDate = cardInfoVO.getRepay24stateEnd();
				endDate = endDate.replaceAll("\\D", "") + "01";
				endDate = DateTool.formatDate(endDate, DateTool.PATTERN_DEFAULT);
				CreditCardEntity creditCardEntity = new CreditCardEntity();
				creditCardEntity.setCardType("1".equals(cardInfoVO.getCardType()) ? CreditCardType.DEBIT_CARD
						: CreditCardType.SEMI_CREDIT_CARD);
				creditCardEntity.setTotalAmt(cardInfoVO.getCardLimit());// 总额
				creditCardEntity.setLoanBalAmt(cardInfoVO.getCardLimit().subtract(cardInfoVO.getUsedAmt()));// 贷款余额
				creditCardEntity.setBankNo(cardInfoVO.getCardLoanOrg());// 行号
				creditCardEntity.setCardStatus(getCardStatus(cardInfoVO.getCardState()));// 卡状态
				creditCardEntity.setCardNo(cardInfoVO.getCardLoanId());
				// creditCardEntity.setCurrMonthUsedAmt(cardInfoVO.getUsedAmt());//当前月使用金额
				// creditCardEntity.setAvgUsedAmt(cardInfoVO.getUsedAmt());//平均使用额度
				List<CreditCardOverdueEntity> overdueInfos = new ArrayList<>();
				String repay_24state = cardInfoVO.getRepay24state();// 近24个月还款情况
				logger.info("近24个月还款情况为: " + repay_24state);
				if (StringUtil.isNotEmpty(repay_24state)) {
					int len = repay_24state.length();
					for (int i = 0; i < len; i++) {
						CreditCardOverdueEntity overdueEntity = new CreditCardOverdueEntity();
						char c = repay_24state.charAt(len - 1 - i);
						String yearMonth = TimeUtil.addMonth(endDate, 0 - i).replaceAll("-", "").substring(0, 6);// yyyyMM
						overdueEntity.setOverDueDate(yearMonth);// 逾期月份
						// 如果是数字
						if (String.valueOf(c).matches(regex)) {
							overdueEntity.setLastOverdueMonth(Integer.parseInt(String.valueOf(c)));// 逾期持续月份
						} else {
							overdueEntity.setLastOverdueMonth(0);// 逾期持续月份
						}
						overdueInfos.add(overdueEntity);
					}
				}
				creditCardEntity.setOverdueInfos(overdueInfos);
				CreditCardOverdueEntity creditCardOverdueEntity = new CreditCardOverdueEntity();
				creditCardOverdueEntity.setOverDueAmt(cardInfoVO.getCurrOverdueAmt());// 当前逾期金额
				creditCardOverdueEntity.setLastOverdueMonth(cardInfoVO.getCurrOverdueNum());// 当前逾期期数
				creditCardEntity.setCurrentOver(creditCardOverdueEntity);
				cards.add(creditCardEntity);//

				// 计算卡累计逾期和连续逾期，默认最近24个月
				int cardOverDueMaxLXTmp = 0;
				String cardOverStatus = cardInfoVO.getRepay24state();
				char[] records = cardOverStatus.toCharArray();
				for (int k = 0; k < records.length; k++) {
					Character aa = new Character(records[k]);
					if (Character.isDigit(aa)) {
						cardOverDueLJ++;// 累计
						cardOverDueMaxLXTmp++;
						if (k == records.length - 1) {
							cardOverDueMaxLX = cardOverDueMaxLXTmp > cardOverDueMaxLX ? cardOverDueMaxLXTmp
									: cardOverDueMaxLX;
							cardOverDueMaxLXTmp = 0;
						}
					} else {
						if (cardOverDueMaxLXTmp > cardOverDueMaxLX) {
							cardOverDueMaxLX = cardOverDueMaxLXTmp;
						}
						cardOverDueMaxLXTmp = 0;
					}
				}
			}
		}
		if (Objects.nonNull(cusRptPromptInfoVO)) {
			// 组装信用卡授信总额度
			creditCardTotalAmt = creditCardTotalAmt.add(cusRptPromptInfoVO.getUNDLoanCardCreditLimit())
					.add(cusRptPromptInfoVO.getUNDSLoanCardCreditLimit());
			// 组装所有的信用卡最近6个月平均使用额度
			sixAvgUsedAmt = sixAvgUsedAmt.add(cusRptPromptInfoVO.getUNDLoanCardUsedAvg6())
					.add(cusRptPromptInfoVO.getUNDSLoanCardUsedAvg6());
		}
		personalCreditEntity.setSixAvgUsedAmt(sixAvgUsedAmt);// 所有的信用卡最近6个月平均使用额度
		personalCreditEntity.setCreditCardTotalAmt(creditCardTotalAmt);// 授信总额度
		personalCreditEntity.setCards(cards);
		personalCreditEntity.setCardDebitOverdueAllNum(cardOverDueLJ);// 累计逾期
		personalCreditEntity.setCardContiOverdueNum(cardOverDueMaxLX);// 最大连续逾期
		/*************** 个人征信卡信息对象，含贷款/贷记卡/准贷记卡 end ***************/

		/*************** 特殊交易 start ***************/
		if (Objects.nonNull(cusRptPromptInfoVO)) {
			personalCreditEntity.setLoanSpeTreansFlag(
					cusRptPromptInfoVO.getAssureRepayCount() > 0 || cusRptPromptInfoVO.getAssetDissCount() > 0);
		} else {
			personalCreditEntity.setLoanSpeTreansFlag(false);
		}
		/*************** 特殊交易 end ***************/

		/*************** 行内贷款信息 start ***************/
		BankInnerLoanEntity innerLoan = new BankInnerLoanEntity();
		if(cusPrelistRiskInfoVo!=null) {
		
	      innerLoan.setOverdueLoanFlag(BaseConstant.YES.equals( cusPrelistRiskInfoVo.getLoanOdInd()));
		}
		else
			innerLoan.setOverdueLoanFlag(false);
		
		if(!StringUtil.isNullorBank(firstDisbDate))
	    	innerLoan.setFirstDisbDate(firstDisbDate);
	
		//innerLoan.setOnlyLegalCreditAmt(cusPrelistRiskInfoVo.getLegalOrgTotalLmtamt());// 客户单法人授信金额
	//	innerLoan.setTotalCreditAmt(cusPrelistRiskInfoVo.getBankTotalLmtamt());// 法人机构授信总额度
		//innerLoan.setNonSettleOrgNum(cusRptPromptInfoVO == null ? 0 : cusRptPromptInfoVO.getUNPLoanFinCorpCount());// 未结清贷款法人机构数
		/*************** 行内贷款信息 end ***************/

		ruleArgsEntity.setCredit(personalCreditEntity);// 征信信息
		ruleArgsEntity.setInnerLoan(innerLoan);// 行内贷款信息

		return ruleArgsEntity;
	}

	/**
	 * 判断查询类型
	 * 
	 * @param queryCase
	 * @return
	 */
	public static CreditQueryType judgeQueryReason(String queryCase) {
		String qCase = queryCase == null ? "" : queryCase.trim();
		switch (qCase) {
		case "贷款审批":
			return CreditQueryType.LOAN_APPR;
		case "信用卡审批":
			return CreditQueryType.CREDIT_CARD_APPR;
		case "贷后管理":
			return CreditQueryType.LOAN_AFTER_MANAGE;
		default:
			return CreditQueryType.OTHER;
		}
	}

	/**
	 * 获取查询日期，转换为 yyyy-MM-dd
	 * 
	 * @param queryDate
	 * @return
	 */
	public static String getQueryDate(String queryDate) {
		if (StringUtil.isEmpty(queryDate)) {
			return "";
		}
		String date = queryDate.replaceAll("\\D", "");// 替换所有非数字字符
		date = date.substring(0, 8);
		date = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8);
		return date;
	}

	/**
	 * 获取行号
	 * 
	 * @param queryUser
	 * @return
	 */
	public static String getBankNo(String queryUser) {
		if (StringUtil.isEmpty(queryUser)) {
			return "";
		}
		String[] arr = queryUser.split("/");
		return arr[0];
	}

	/**
	 * 获取行号
	 * 
	 * @param queryUser
	 * @return
	 */
	public static String getQueryUser(String queryUser) {
		if (StringUtil.isEmpty(queryUser)) {
			return "";
		}
		String[] arr = queryUser.split("/");
		return arr.length == 2 ? arr[1] : arr[0];
	}

	/**
	 * 获取贷款类型
	 * 
	 * @param loanPrd
	 * @return
	 */
	public static LoanType getLoanType(String loanPrd) {
		String type = loanPrd == null ? "" : loanPrd.trim();
		if (type.indexOf("个人消费贷款") != -1 || type.indexOf("消费贷款") != -1) {
			return LoanType.CONSUME;
		} else if (type.indexOf("个人经营性贷款") != -1 || type.indexOf("经营性贷款") != -1) {
			return LoanType.OPERATE;
		} else if (type.indexOf("个人住房贷款") != -1 || type.indexOf("住房贷款") != -1 || type.indexOf("个人住房公积金贷款") != -1
				|| type.indexOf("住房公积金贷款") != -1 || type.indexOf("个人商用房（包括商住两用）贷款") != -1
				|| type.indexOf("商用房（包括商住两用）贷款") != -1) {
			return LoanType.HOUSE;
		} else {
			return LoanType.OTHER;
		}
	}

	/**
	 * 获取卡状态
	 * 
	 * @param cardStatus
	 * @return
	 */
	public static CardStatus getCardStatus(String cardStatus) {
		String status = cardStatus == null ? "" : cardStatus.trim();
		switch (status) {
		case "正常":
			return CardStatus.NORMAL;
		case "逾期":
			return CardStatus.OVERDUE;
		case "呆账":
			return CardStatus.BAD_DEBT;
		case "冻结":
			return CardStatus.FROZEN;
		case "止付":
			return CardStatus.STOP_PAYMENT;
		case "结清":
			return CardStatus.SETTLE;
		case "异常":
			return CardStatus.EXCEPTION;
		case "挂失":
			return CardStatus.REPORT_LOSE;
		case "销户":
			return CardStatus.CACEL_ACCOUNT;
		case "核销":
			return CardStatus.CANCEL_AFTER_VERIFI;
		case "未激活":
			return CardStatus.NO_ACTIVATION;
		default:
			return CardStatus.OTHER;
		}
	}

	/**
	 * 获取风险分类
	 * 
	 * @param fiveLevel
	 * @return
	 */
	public static RiskClassfyType getRiskClassfyType(String fiveLevel) {
		String level = fiveLevel == null ? "" : fiveLevel;
		switch (level) {
		case "正常":
			return RiskClassfyType.NORMAL_ONE;
		case "关注":
			return RiskClassfyType.FOCUS_ONE;
		case "可疑":
			return RiskClassfyType.SUSPICIOUS;
		case "次级":
			return RiskClassfyType.SECONDARY;
		case "损失":
			return RiskClassfyType.LOSS;
		default:
			return RiskClassfyType.NONE;
		}
	}

	/**
	 * 获取担保方式
	 * 
	 * @param guarType
	 * @return
	 */
	/*
	 * private GuaranteeType getGuaranteeType(String guarType) { String type =
	 * guarType==null?"":guarType; switch (type) { case "免担保": return
	 * GuaranteeType.CREDIT; case "组合(不含保证)担保": return GuaranteeType.GUAR; case
	 * "抵押担保": return GuaranteeType.MORTGAGE; case "质押担保": return
	 * GuaranteeType.PLEDGE; default : return GuaranteeType.OTHER; } }
	 */

	public static GuaranteeType getGuaranteeType(String guarType) {
		if (StringUtils.isEmpty(guarType))
			return GuaranteeType.OTHER;

		if (guarType.indexOf("免担保") != -1 || guarType.indexOf("信用") != -1) {
			return GuaranteeType.CREDIT;
		} else if (guarType.indexOf("组合(不含保证)担保") != -1) {
			return GuaranteeType.GUAR;
		} else if (guarType.indexOf("抵押担保") != -1) {
			return GuaranteeType.MORTGAGE;
		} else if (guarType.indexOf("质押担保") != -1) {
			return GuaranteeType.PLEDGE;
		} else
			return GuaranteeType.OTHER;
	}

	public static LoanStatus getLoanStatus(String loanStatus) {
		if (StringUtils.isEmpty(loanStatus)) {
			return LoanStatus.OTHER;
		} else {
			switch (loanStatus) {
			case "正常":
				return LoanStatus.NORMAL;
			case "结清":
				return LoanStatus.CLOSE_OVER;
			default:
				return LoanStatus.OTHER;
			}
		}

	}
}
